package top.ieei.demo.tftp;

import java.io.File;
import java.net.SocketException;
import java.util.Locale;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * TFTP 服务<br>
 * @author xiecongshu
 */
public class TftpServer
{
    /**
     * 日志
     */
    private static final Log LOG = LogFactory.getLog(TftpServer.class);
    
    /**
     * TFTP服务绑定IP
     */
    public static String tftpIp = "127.0.0.1";
    
    /**
     * TFTP默认端口
     */
    private static final int DEFAULT_PORT = 69;
    
    /**
     * 部署任务最高并发20个，所以设置能同时处理20个，实际上请求TFTP请求很难同时20个并发请求
     */
    private int poolSize = 20;
    
    /**
     * TFTP服务端口
     */
    private int port = DEFAULT_PORT;
    
    /**
     * TFTP服务目录
     */
    public static String tftpRoot = "/";
    
    /**
     * TFTP服务套接字
     */
    private ServerSocket serverSocket;
    
    /**
     * 
     * 构造函数<br>
     * @author xiecongshu
     * @since  1.0, 2013-4-25
     * @param tftpHome
     * @param port
     */
    public TftpServer(String tftpHome, int port)
    {
        tftpHome = getTftpHome(tftpHome);
        if (null != tftpHome)
        {
            TftpServer.tftpRoot = tftpHome;
        }
        if (port > 0 && port < 65536)
        {
            this.port = port;
        }
    }
    
    /**
     * 获取TFTP服务目录
     * @param tftpHome
     * @return String
     */
    public String getTftpHome(String tftpHome)
    {
        if (null != tftpHome && !tftpHome.isEmpty())
        {
            File dir = new File(tftpHome);
            if (!dir.exists() || dir.isFile())
            {
                if (!dir.mkdirs())
                {
                    LOG.error("Failed to initialize the TFTP service directory. Change it to default directory:/");
                    return null;
                }
            }
            
            String osName = System.getProperty("os.name");
            if (!osName.toUpperCase(Locale.ENGLISH).startsWith("WIN"))
            {
                if (!tftpHome.endsWith("/"))
                {
                    tftpHome += '/';
                }
            }
        }
        return tftpHome;
    }
    
    /**
     * 获取TFTP服务监听端口
     * 
     * @return int
     */
    public int getPort()
    {
        return port;
    }
    
    /**
     * 设置TFTP服务监听端口
     * 
     * @param port 
     */
    public void setPort(int port)
    {
        this.port = port;
    }
    
    /**
     * 设置TFTP服务工作池大小
     * 
     * @param size The size to set
     */
    public void setPoolSize(int poolSize)
    {
        this.poolSize = poolSize;
        if (serverSocket == null)
        {
            return;
        }
        serverSocket.setPoolSize(poolSize);
    }
    
    /**
     * 获取TFTP服务工作池大小
     * 
     * @return int
     */
    public int getPoolSize()
    {
        return poolSize;
    }
    
    /**
     * 启动TFTP服务，开启TFTP服务监听
     * 
     * @throws SocketException
     */
    public void start() throws SocketException
    {
        LOG.info("Starting new TFTP server socket on port: " + port);
        serverSocket = new ServerSocket(port, poolSize);
        serverSocket.start();
    }
    
    /**
     * 关闭TFTP服务，关闭TFTP服务监听
     */
    public void stop()
    {
        if (null == serverSocket)
        {
            LOG.error("ServerSocket is already null,TftpServer has closed?");
            return;
        }
        LOG.info("Shutting down TFTP server socket now.");
        serverSocket.stop();
        serverSocket = null;
    }
    
    /**
     * TFTP服务是否运行中
     * @return boolean
     */
    public boolean isRunning()
    {
        if (null == serverSocket)
        {
            return false;
        }
        
        return true;
    }
    
    public static void main(String[] args)
    {
        TftpServer server = new TftpServer("D:/tftpboot/", 69);
        try
        {
            server.start();
        }
        catch (SocketException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
